#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys

sys.path.append("/work/opt/analytic/my_python")
from lib.format_time import *
from lib.HandleMysql import *
from lib.handle_mongo import *
from lib.switch_code import *
from lib.load_data import *
from topinfo_conn import *
import re
import time

reload(sys)
sys.setdefaultencoding('utf-8')


def get_order_info(date, conn, num):
    stat_conn = set_stats_conn()
    stat_table = "top_info_tmp"

    line_list = []

    query = "select id,order_id,account_type,buss_type,order_type,order_money,refund_money,project_id,product_name,show_type,create_time from orders where mer_id=1022 and date(finish_time)='%s' " % date
    items = conn.get_results(query)
    for item in items:

        order_code = item[1]
        if order_code == None:
            continue
        if order_code.find('t') == -1:
            continue

        order_id = item[0]
        order_code = order_code.replace('topInfo', '')
        order_code = order_code.replace('Project', '')

        param = [order_code, order_id, num, date]
        line_list.append('\t'.join(map(lambda i: str(i), param)))
        #print  param;

    cont = '\n'.join(line_list)
    path = "/work3/opt/analytic/lh_tmp_data/topinfo_data/tmp/"
    file_name = "top_info_order_tmp_%s_%s.txt" % (date.replace('-', ""), num)
    writeTextToFile(path, file_name, "w", cont)

    if num == 0:
        q = "delete from top_info_tmp where stat_date='%s'" % date
        stat_conn.execute_sql(q)

    load_data(stat_conn, path + file_name, stat_table, '\t')

    conn.close()
    stat_conn.close()


def top_info_pay(date):
    conn = set_stats_conn()
    top_conn = set_top_conn()

    order_conn = None
    order_conn0 = set_order0_conn()
    order_conn1 = set_order1_conn()
    order_conn2 = set_order2_conn()
    order_conn3 = set_order3_conn()
    stat_table = "top_info_pay"

    line_list = []
    #return 
    query = "select topinfoid,topid,amount from topinfo_topinfo where date(addtime)='%s' order by topinfoid asc" % date
    items = top_conn.get_results(query)
    for item in items:
        top_info_id = item[0]
        top_id = item[1]
        amount = item[2]

        cash_amount = 0.0
        discount_amount = 0.0
        refund_cash_amount = 0.0
        refund_discount_amount = 0.0
        order_id = 0
        num = 0
        query_id = top_info_id

        if amount == 0:
            q = "select project_id from top_info_project where top_id=%s" % top_id
            its = conn.get_results(q)
            if len(its) > 0:
                query_id = its[0][0]

        q = "select order_id,num from top_info_tmp where top_info_id=%s" % query_id
        its = conn.get_results(q)
        if len(its) > 0:
            order_id = its[0][0]
            num = its[0][1]
        if num == 0:
            order_conn = order_conn0
        elif num == 1:
            order_conn = order_conn1
        elif num == 2:
            order_conn = order_conn2
        else:
            order_conn = order_conn3

        if order_id > 0:
            q = "select order_money,from_account_type,ifnull(refund_money,0) from sub_order where order_id='%s'" % order_id
            its = order_conn.get_results(q)
            if len(its) > 0:
                for it in its:
                    order_amount = it[0]
                    amount_type = it[1]
                    refund_money = it[2]
                    if amount_type == 3:
                        discount_amount += float(order_amount)
                        refund_discount_amount += float(refund_money)
                    else:
                        cash_amount += float(order_amount)
                        refund_cash_amount += float(refund_money)
        else:
            continue

        #print "4"
        param = [top_info_id, cash_amount, discount_amount, refund_cash_amount, refund_discount_amount, date]
        line_list.append('\t'.join(map(lambda i: str(i), param)))
        #print  param;

    cont = '\n'.join(line_list)
    path = "/work3/opt/analytic/lh_tmp_data/topinfo_data/tmp/"
    file_name = "top_info_pay_%s.txt" % date.replace('-', "")
    writeTextToFile(path, file_name, "w", cont)

    q = "delete from top_info_pay where stat_date='%s'" % date
    conn.execute_sql(q)

    load_data(conn, path + file_name, stat_table, '\t')

    top_conn.close()
    conn.close()
    order_conn0.close()
    order_conn1.close()
    order_conn2.close()
    order_conn3.close()


def execute(date, inp):
    try:
        pass
        order_conn = set_order0_conn()
        get_order_info(date, order_conn, 0)
        order_conn = set_order1_conn()
        get_order_info(date, order_conn, 1)
        order_conn = set_order2_conn()
        get_order_info(date, order_conn, 2)
        order_conn = set_order3_conn()
        get_order_info(date, order_conn, 3)
    except Exception, e:
        print 'get_order_info:', e
    try:
        pass
        top_info_pay(date)
    except Exception, e:
        print 'top_info_pay:', e


def main():
    inp = "0"
    if len(sys.argv) == 1:
        start_date = get_yesterday()
        end_date = start_date
    elif len(sys.argv) == 2:
        start_date = format_date(sys.argv[1])
        end_date = start_date
    elif len(sys.argv) == 3:
        start_date = format_date(sys.argv[1])
        end_date = format_date(sys.argv[2])
    stat_date = start_date
    while stat_date >= start_date and stat_date <= end_date:
        print "The program of the date of %s is beginning at %s " % (stat_date, get_now())
        execute(stat_date, inp)
        #get_top_info_detail(stat_date)
        #get_top_info_user_tmp(stat_date)
        print "The program of the date of %s is end at %s " % (stat_date, get_now())
        stat_date = var_date(stat_date)


if __name__ == '__main__':
    main()
